package org.gd.rest.jersey.client;

import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.WebResource;

import javax.ws.rs.core.MediaType;
import java.util.concurrent.Callable;
import java.util.concurrent.CountDownLatch;

public class AcquiringCreateCallable implements Callable<ClientResponse> {

    private String content;
    private String path;
    private CountDownLatch latch;

    public AcquiringCreateCallable(String content, String path, CountDownLatch latch) {
        this.content = content;
        this.path = path;
        this.latch = latch;
    }

    @Override
    public ClientResponse call() throws Exception {
        latch.await();
        long t = System.currentTimeMillis();
        Client client = Client.create();
        WebResource webResource = client
                .resource(path);
        ClientResponse response = webResource
                .entity(content, MediaType.APPLICATION_XML)
                .accept(MediaType.APPLICATION_XML)
                .get(ClientResponse.class);
        if (response.getStatus() != 200) {
            System.err.println("Failed : HTTP error code : " + response.getStatus());
        }
        String output = response.getEntity(String.class);
        System.out.printf("Output from Server .... %s (t: %s ms)\n",
                output,
                System.currentTimeMillis() - t);
        return response;
    }
}
